<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>在线客服系统</title>
    <script src="/x-admin/js/vue.js"></script>
    <script src="/x-admin/js/common.js"></script>
    <script src="/f-chat/components/jquery/dist/jquery.min.js"></script>
    <script src="/f-chat/components/layui/layui.js"></script>
    <script src="/f-chat/components/layui/lay/modules/element.js"></script>
    <link rel="stylesheet" type="text/css" href="/f-chat/components/layui/css/layui.css">
    <link rel="stylesheet" type="text/css" href="/f-chat/public/stylesheets/style.css"/>
</head>

<body style="background-color: #333;height: 100%">

<div id="container">
    <div class="wc-chat"
         style="z-index: 19980905; width: 270px; height: 500px; background-image: url('/f-chat/public/images/tooopen_sy_160431234145.jpg');"
         onselectstart="return false">

        <div class="title-move" style="cursor:move;">
            <a href="javascript:;" class="func-click" data-type="logout"><i class="layui-icon">&#x1006;</i></a>
        </div>

        <div class="info-group">
            <img :src="self.head"/>
            <span class="u-name">{{self.name}}</span>
            <input placeholder="" value=" ~~~^_^~~~ " id="signature" disabled="true">
        </div>

        <!-- 切换面板 -->
        <ul class="nav-group">
            <li @click="selectTab='friend'">
                <a href="javascript:;" class="func-click" data-type="showfriend">
                    <i class="layui-icon">&#xe612;</i>
                </a>
            </li>
            <!--<li @click="selectTab='group';alert('组聊天待开发')">-->
            <!--<a href="javascript:;" class="func-click" data-type="showgroup">-->
            <!--<i class="layui-icon">&#xe613;</i>-->
            <!--</a>-->
            <!--</li>-->
        </ul>

        <!-- 联系人列表 -->
        <div class="friend-group" v-show="selectTab=='friend'">
            <ul class="layui-nav layui-nav-tree" lay-filter="fuc">
                <li class="layui-nav-item">
                    <a href="javascript:void(0);">客户<em>( {{friends.length}} )</em></a>
                    <dl class="layui-nav-child">
                        <dd v-for="friend in friends"
                            @click="chatTarget=friend;records=[];friend.msgNum=0;selfSingleAction()">
                            <img :src="friend.head"/><span>{{friend.name}}  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{friend.msgNum?friend.msgNum+"条未读消息":""}}</span>

                            <p>(^o^)/YES！</p>
                        </dd>
                    </dl>
                </li>
            </ul>
        </div>

        <div class="friend-group" v-show="selectTab=='group'">
            <ul class="layui-nav layui-nav-tree" lay-filter="fuc">
                <li class="layui-nav-item">
                    <a href="javascript:void(0);">群聊<em>( {{groups.length}} )</em></a>
                    <dl class="layui-nav-child">
                        <dd v-for="group in groups" @click="alert('组聊天待开发')">
                            <img :src="group.head"/><span>{{group.name}}</span>
                            <p>(^o^)/YES！</p>
                        </dd>
                    </dl>
                </li>
            </ul>
        </div>
    </div>
    <!-- 聊天窗口 -->
    <div class="dialog-box" id="dialogBox" v-show="chatTarget.head"
         style="z-index: 19891014; width: 600px; height: 574px; top: 10%; left: 30%; min-width: 500px; min-height: 420px; background-image: url('http://webos.90zs.net/themes/layui/css/modules/layim/skin/3.jpg');">
        <!-- 可以拖动处 -->
        <div class="title-move" style="cursor:move;">
            <a href="javascript:;" class="func-click" data-type="close"><i class="layui-icon" style="color: #0C0C0C"
                                                                           @click="chatTarget={}">&#x1006;</i></a>
        </div>
        <div class="main-chat">
            <div class="box-chat">
                <div class="title-chat">
                    <img :src="chatTarget.head"/>
                    <span class="u-name">{{ self.name }}</span>
                    <p>(^o^)/YES！</p>
                    <br>
                </div>
                <div class="content-chat">
                    <ul>
                        <li v-for="record in records" :class="{'mine-chat':record.sender==self.id}">
                            <div class="user-chat">
                                <img :src="(record.sender==self.id)?self.head:chatTarget.head">
                                <cite v-if="record.sender==self.id"><i>{{record.chatTime |
                                    time}}</i>{{record.name}}</cite>
                                <cite v-else>{{record.name}}<i>{{record.chatTime | time}}</i></cite>
                            </div>
                            <div class="text-chat" v-html="record.content">{{record.content}}</div>
                        </li>
                    </ul>
                </div>

                <div class="editor-chat">
                    <div class="textarea-chat">
							<textarea class="layui-textarea" id="msgfor-send" style="display: none">

							</textarea>
                    </div>
                    <div class="bottom-chat">
                        <div class="send-chat">
                            <a href="javascript:;" class="func-click" @click="chatTarget={};records=[]">关闭</a>
                            <a href="javascript:;" class="btn-send" @click="send">发送</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/f-chat/public/js/date.js"></script>
<script>

    Notification.requestPermission();

    function sendDesktopNotify(user, msg) {
        var notification = new Notification("您有新的通知！（" + user + "）", {
            body: msg,
            icon: 'http://img06.tooopen.com/images/20160712/tooopen_sy_170083325566.jpg',
            dir: 'auto',
        });
        setTimeout(function () {
            notification.close()
        }, 5000)
    }

    function getToken(kf) {
        if (!kf) {
            alert("客服信息缺失,请重新选择客服！");
            return;
        }

        if (sessionStorage.getItem("chat-token")) {
            return sessionStorage.getItem("chat-token");
        }

        var selfToken = "";
        $.ajax({
            url: '/kf/tempRelation?kfId=' + kf,
            async: false,
            context: document.body,
            success: function (data) {
                selfToken = data.data;
                if (selfToken)
                    sessionStorage.setItem("chat-token", selfToken);
            }
        });

        return selfToken;
    }


    var token = getParam("token") ? getParam("token") : getToken(getParam("kf"));

    if (!token) {
        alert("未获取到token！");
        throw new Error("未获取到token！");
    }


    var layedit, index;

    var listFriend = new Vue({
        el: '#container',
        data: {
            self: {},
            selectTab: "friend",
            records: [],
            friends: [],
            groups: [],
            chatTarget: {},
            ws: null
        },
        filters: {
            time: function (time) {
                return time ? new Date(time).Format("yyyy-MM-dd HH:mm:ss") : new Date().Format("yyyy-MM-dd HH:mm:ss");
            }
        },
        methods: {
            send: function () {
                var text = layedit.getContent(index)
                if (text.length > 0) {

                    var msg = {
                        uinId: this.guid(),
                        sender: this.self.id,
                        receiver: this.chatTarget.id,
                        msgType: "text",
                        content: text,
                        type: "singleChat",
                        name: this.self.name,
                        head: this.self.head,
                        extra: {}
                    };
                    var data = {type: "chat", msg: JSON.stringify(msg)};
                    this.ws.send(JSON.stringify(data));
                    this.records.push(msg)
                }

                layui.use('layer', function () {
                    layer.msg('已发送');
                });

                $('.content-chat').scrollTop(99999999999);
            },
            isInFriendList: function (id) {
                for (var index in this.friends) {
                    if (id == this.friends[index].id) {
                        return this.friends[index];
                    }
                }
                return null;
            },
            message: function (messageEvent) {
                var msg = JSON.parse(JSON.parse(messageEvent.data).msg);

                if (msg && msg.type == "singleChat") {

                    sendDesktopNotify(msg.sender, msg.content)

                    if (this.chatTarget.id == msg.sender) {
                        this.records.push(msg);
                    } else {
                        layer.msg("您有新的消息！");
                        var friend = this.isInFriendList(msg.sender);
                        if (!friend) {
                            var user = [{
                                name: "临时会话：" + msg.sender,
                                head: "http://doll-img.oss-cn-shanghai.aliyuncs.com/2017/12/34942974513119232.png",
                                id: msg.sender
                            }]
                            this.friends = user.concat(this.friends);
                        } else {
                            Vue.set(friend, 'msgNum', (friend.msgNum ? (friend.msgNum + 1) : 1));
                        }
                    }
                    return
                }

                if (msg && msg.type == "friends") {
                    this.friends = msg.friends;
                    return
                }

                if (msg && msg.type == "self") {
                    this.self = msg.self;
                    this.friendAction();
                    return
                }

                if (msg && msg.type == "history") {
                    this.records = msg.chatMsg.reverse().concat(this.records);
                    return
                }

                setTimeout(function () {
                    $('.content-chat').scrollTop(99999999999);
                }, 2000)
            },
            friendAction: function () {
                var msg = {
                    sender: this.self.id,
                    type: "friend"
                };
                var data = {type: "chat", msg: JSON.stringify(msg)};
                this.ws.send(JSON.stringify(data));
            },
            selfAction: function () {
                var data = {type: "self"};
                this.ws.send(JSON.stringify(data));
            },
            selfSingleAction: function () {
                var msg = {
                    self: this.self.id,
                    receiver: this.chatTarget.id,
                    type: "singleHistory",
                    last: (this.records.length > 0 ? this.records[0].id : 0)
                };
                var data = {type: "chat", msg: JSON.stringify(msg)};
                this.ws.send(JSON.stringify(data));
            },
            close: function () {

            },
            open: function () {
                this.selfAction();
            },
            error: function () {

            },
            guid: function () {
                function S4() {
                    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                }

                return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
            },
            initWs: function () {
                this.ws = new WebSocket(((document.location.protocol == "http:") ? "ws" : "wss") + "://" + window.location.hostname + ":8080?ZMM-SESSION-TOKEN=" + token)
                this.ws.onmessage = this.message
                this.ws.onclose = this.close
                this.ws.onopen = this.open
                this.ws.onerror = this.error
            }
        },
        mounted: function () {
            //初始化导航
            layui.use('element', function () {
                layui.element();
            });
            //初始化编辑器
            layui.use('layedit', function () {
                layedit = layui.layedit;
                //初始化发送文本框
                index = layedit.build('msgfor-send', {
                    tool: ['left', 'center', 'right']
                    , height: 100
                })
            });
            this.initWs();
        }
    })


</script>
</body>
</html>
